package cn.edu.bupt.freewings.forum.server.rest.providers;

import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;

import com.google.protobuf.Message;

@Consumes("application/proto")
@Provider
public class ProtoBufferReader implements MessageBodyReader<Message> {

	static MediaType	protoMediaType	= MediaType.valueOf("application/proto");

	public boolean isReadable(Class<?> clasz, Type type,
			Annotation[] annotations, MediaType mediaType) {
		return Message.class.isAssignableFrom(clasz)
				&& mediaType.isCompatible(protoMediaType);
	}

	public Message readFrom(Class<Message> clasz, Type type,
			Annotation[] annotations, MediaType mediaType,
			MultivaluedMap<String, String> httpHeaders, InputStream inputStream)
			throws IOException, WebApplicationException {
		try {
			java.lang.reflect.Method parseFrom = clasz.getMethod("parseFrom",
					InputStream.class);
			return (Message) parseFrom.invoke(null, inputStream);
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return null;
	}

}
